import store from './store'
export default async function(count = 1, source = 3) {
  const arr = []
  let sources = []
  if (source == 1) sources = ['album']
  else if (source == 2) sources = ['camera']
  else if (source == 3) sources = ['album', 'camera']
  const [err, res] = await uni.chooseImage({
    count,
    sizeType: ['original', 'compressed'],
    sourceType: sources
  })
  if (err) return Promise.reject('用户取消')
  for (const item of res.tempFiles) {
    if (item.size > 5120 * 1024) {
      uni.showToast({
        title: '图片最大5MB',
        icon: 'error',
        duration: 2000
      })
      return []
    }
    const filePath = item.path
    try {
      arr.push(await upload(filePath))
    } catch {
      console.log('==>上传失败 <==')
    }
  }
  uni.showLoading({
    title: '上传中',
    mask: true
  })
  try {
    const list = await Promise.all(arr)
    uni.hideLoading()
    return list
  } catch (e) {
    uni.hideLoading()
    return Promise.reject(e)
  }
}

function upload(filePath) {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: 'https://hsxt.ruyihui.net/api/common/upload',
      filePath,
      name: 'image',
      timeout: 10000,
      header: {
        // 'token': store.state.token
        'token':'0fe60a01-8332-409e-8d01-fdf0d4f9b1bd',
      },
      success: res => {
        // console.log("SON.parse(res.data)",res.data)
        if (res.statusCode !== 200) {
          uni.showToast({
            title: '上传失败',
            icon: 'error',
            mask: true,
            duration: 2000
          })
          reject(res)
          return
        }
        resolve(JSON.parse(res.data).data)
      },
      fail: res => {
        console.log('error')
        uni.showToast({
          title: '上传失败',
          icon: 'error',
          mask: true,
          duration: 2000
        })
        reject(res)
      }
    })
  })
}
